package com.beiing.tianshuai.tianshuai.mine.ui;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.event.EventConstant;
import com.beiing.tianshuai.tianshuai.event.messages.OrderListEvent;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderApplyAfterSaleBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderApplyAfterSalePostDataBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderApplyAfterSalePresenter;
import com.beiing.tianshuai.tianshuai.mine.ui.fragment.OrderExchangeGoodsFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.fragment.OrderRefundFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.fragment.OrderRefundReturnGoodsFragment;
import com.beiing.tianshuai.tianshuai.mine.view.OrderApplyAfterSaleViewImpl;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.netease.nim.uikit.common.util.log.LogUtil;

import java.text.MessageFormat;

import butterknife.BindView;

public class OrderApplyAfterSaleActivity extends BaseActivity implements OrderApplyAfterSaleViewImpl {

    /**
     * root view
     */
    @BindView(R.id.rl_root_view)
    RelativeLayout rlRootView;
    /**
     * toolbar 返回按钮
     */
    @BindView(R.id.toolbar_navigation_back)
    ImageButton toolbarNavigationBack;
    /**
     * toolbar标题
     */
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    /**
     * toolbar 更多
     */
    @BindView(R.id.toolbar_filter_more)
    ImageButton toolbarFilterMore;
    /**
     * 商品照片
     */
    @BindView(R.id.iv_ex_tickets)
    ImageView ivExTickets;
    /**
     * 商品数量
     */
    @BindView(R.id.tv_goods_number)
    TextView tvGoodsNumber;
    /**
     * 商品名称
     */
    @BindView(R.id.tv_after_sale_name)
    TextView tvAfterSaleName;
    /**
     * 商品种类
     */
    @BindView(R.id.tv_after_sale_kinds)
    TextView tvAfterSaleKinds;
    /**
     * 上部分蓝色商品状态显示框
     */
    @BindView(R.id.rl_goods_after_sale)
    RelativeLayout rlGoodsAfterSale;
    /**
     * 仅退款选项布局
     */
    @BindView(R.id.rl_refund)
    RelativeLayout rlRefund;
    /**
     * 退货退款选项布局
     */
    @BindView(R.id.rl_refund_return_goods)
    RelativeLayout rlRefundReturnGoods;
    /**
     * 换货选项布局
     */
    @BindView(R.id.rl_exchange_goods)
    RelativeLayout rlExchangeGoods;
    /**
     * 申请售后显示布局 ，点击隐藏
     */
    @BindView(R.id.rl_choose_back_type)
    RelativeLayout rlChooseBackType;
    /**
     * 填充fragment布局容器，点击显示
     */
    @BindView(R.id.fl_fragment_container)
    FrameLayout flFragmentContainer;
    /**
     * 订单id
     */
    private String mOrderId;
    /**
     * 货物数量
     */
    private String mGoodsNumber;
    /**
     * 货物名称
     */
    private String mGoodsName;
    /**
     * 货物照片
     */
    private String mGoodsPhoto;

    /**
     * 货物种类
     */
    private String mGoodsKind;
    /**
     * 返回全部价格
     */
    private String mGoodsPriceAll;
    /**
     * 货物价格
     */
    private String mGoodsPrice;
    /**
     * 运费
     */
    private String mGoodsFreight;
    /**
     * Fragment管理器
     */
    private FragmentManager mFragmentManager;
    /**
     * Fragment交易
     */
    private FragmentTransaction fragmentTransaction;
    /**
     * 仅退款Fragment
     */
    private OrderRefundFragment mOrderRefundFragment;
    /**
     * 退货退款Fragment
     */
    private OrderRefundReturnGoodsFragment mOrderRefundReturnGoodsFragment;
    /**
     * 换货Fragment
     */
    private OrderExchangeGoodsFragment mOrderExchangeGoodsFragment;
    /**
     * 申请售后Presenter
     */
    private OrderApplyAfterSalePresenter mPresenter;
    /**
     * 商品单价
     */
    private String mPrice;
    /**
     * 运费
     */
    private String mFreight;
    /**
     * 总价
     */
    private String mTotalPrice;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_apply_after_sale;
    }

    @Override
    protected void init() {
        //showShortText("welcome");
        initIntentExtras();
        initPresenter();
        initListener();
        mFragmentManager = getSupportFragmentManager();
        Log.i(mOrderId + mGoodsPriceAll + mGoodsKind + mGoodsPhoto, "获取的数据");
    }

    private void initPresenter() {
        //分析错误，只需要传递订单号就可以
        mPresenter = new OrderApplyAfterSalePresenter(this);
        mPresenter.getOrderApplyAfterSale(mOrderId);
    }

    private void initListener() {
        rlRefund.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i("仅退款", "1");
                rlChooseBackType.setVisibility(View.GONE);
                flFragmentContainer.setVisibility(View.VISIBLE);
                selectFragment(0);
            }
        });
        rlRefundReturnGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("退货退款", "2");
                rlChooseBackType.setVisibility(View.GONE);
                selectFragment(1);
            }
        });
        rlExchangeGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("换货", "3");
                rlChooseBackType.setVisibility(View.GONE);
                selectFragment(2);

            }
        });
        toolbarNavigationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("========结束========", "finish");
                finish();
            }
        });
    }

    private void selectFragment(int index) {
        fragmentTransaction = mFragmentManager
                .beginTransaction();
        //RemoveFragment(fragmentTransaction);
        hideFragment(fragmentTransaction);
        switch (index) {
            case 0:
                //仅退款
                toolbarTitle.setText("申请退款");
                if (mOrderRefundFragment == null) {
                    mOrderRefundFragment = OrderRefundFragment.getInstance(mOrderId, mPrice, mFreight, mTotalPrice);
                    fragmentTransaction.add(R.id.fl_fragment_container, mOrderRefundFragment);
                }
                fragmentTransaction.show(mOrderRefundFragment);
                break;
            case 1:
                //退货退款
                toolbarTitle.setText("申请退货退款");
                if (mOrderRefundReturnGoodsFragment == null) {
                    mOrderRefundReturnGoodsFragment = OrderRefundReturnGoodsFragment.getInstance(mOrderId, mPrice, mFreight, mTotalPrice);
                    fragmentTransaction.add(R.id.fl_fragment_container, mOrderRefundReturnGoodsFragment);
                }
                fragmentTransaction.show(mOrderRefundReturnGoodsFragment);
                break;
            case 2:
                //换货
                toolbarTitle.setText("申请换货");
                if (mOrderExchangeGoodsFragment == null) {
                    mOrderExchangeGoodsFragment = OrderExchangeGoodsFragment.getInstance(mOrderId);
                    fragmentTransaction.add(R.id.fl_fragment_container, mOrderExchangeGoodsFragment);
                }
                fragmentTransaction.show(mOrderExchangeGoodsFragment);
                break;
            default:
                break;
        }
        fragmentTransaction.commit();
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (mOrderRefundFragment != null) {
            fragmentTransaction.hide(mOrderRefundFragment);
        }
        if (mOrderRefundReturnGoodsFragment != null) {
            fragmentTransaction.hide(mOrderRefundReturnGoodsFragment);
        }
        if (mOrderExchangeGoodsFragment != null) {
            fragmentTransaction.hide(mOrderExchangeGoodsFragment);
        }

    }

    /**
     * 开启Activity 获取参数
     *
     * @param context 上下文
     * @param orderId 订单id
     */
    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderApplyAfterSaleActivity.class);
        intent.putExtra("orderId", orderId);
        //强转返回参数,请求码
        ((Activity) context).startActivityForResult(intent, AppConstant.REQUEST_CODE_APPLY_REFRESH);
    }

    /**
     * 获取传递的数据
     */
    private void initIntentExtras() {
        Intent intent = getIntent();
        mOrderId = intent.getStringExtra("orderId");

    }

    /**
     * 获取根视图
     *
     * @return root view
     */
    public RelativeLayout getRlRootView() {
        return rlRootView;
    }

    /**
     * 请求售后订单信息获取成功
     *
     * @param bean 请求数据
     */
    @Override
    public void getOrderApplyAfterSaleSuccess(OrderApplyAfterSaleBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                tvAfterSaleName.setText(bean.getData().get(0).getStrech());
                tvAfterSaleKinds.setText(MessageFormat.format("分类：{0}", bean.getData().get(0).getTicketType()));
                tvGoodsNumber.setText(MessageFormat.format("共{0}件商品", bean.getData().get(0).getCount()));

                mPrice = bean.getData().get(0).getPrice();
                mFreight = bean.getData().get(0).getFreight();
                mTotalPrice = bean.getData().get(0).getAmountMoney();

                //非票务类照片比例参数
                RequestOptions goodsPhotoOptions = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .placeholder(R.drawable.default_avatar)
                        .override(90, 90);
                //非票务类图片
                Glide.with(mContext.getApplicationContext())
                        .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + bean.getData().get(0).getCover())
                        .apply(goodsPhotoOptions)
                        .into(ivExTickets);
                //获取价格数据进入到Fragment
                break;
            case 401:
                showShortText("参数错误");
                break;
            case 202:
                showShortText("执行失败");
                break;
            default:
                showShortText("未知参数"+code);
                LogUtil.e("申请售后","未知参数"+code);
                break;
        }
    }

    @Override
    public void getOrderApplyAfterSaleError(Throwable throwable) {
        showShortText("请求订单信息失败");
    }

    /**
     * 上传退货信息成功
     *
     * @param bean 上传数据
     */
    @Override
    public void postOrderApplyAfterSaleInfoSuccess(OrderApplyAfterSalePostDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("申请售后成功");
                //返回结果码给订单详情页
                setResult(AppConstant.RESULT_CODE_APPLY_TO_ORDER_DETAIL);

                //申请售后成功发送消息通知消息列表页更新
                RxBus.getInstanceBus().post(
                        new OrderListEvent<>(
                                EventConstant.EVENT_TYPE_UPDATE_ORDER_LIST,
                                "申请售后成功")
                );

                finish();
                break;
            case 401:
                showShortText("参数错误");
                break;
            case 202:
                showShortText("执行失败,已经退货完成");
                break;
            default:
                showShortText("未知参数"+code);
                break;
        }
    }

    @Override
    public void postOrderApplyAfterSaleInfoError(Throwable throwable) {
        showShortText("发送退货信息失败"+throwable);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(OrderApplyAfterSaleBean bean) {
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("请求失败"+throwable);
    }

    /**
     * 获取当前activity的presenter对象
     *
     * @return presenter
     */
    public OrderApplyAfterSalePresenter getPresenter() {
        return mPresenter;
    }
}
